import java.util.Random;

/**
 * @author Chris Fraser, Jean-Luc Richard
 * This class represents all actions that can be done on a deck of cards
 * such as shuffling a deck, drawing a card, etc.
 */
public class CardGameActions
{
        /**
         * Constructor method
         */
        public CardGameActions()
        {
        }
       
        /**
         *  This method shuffles a CardDeck's deck using a pseudo-random generator
         * @param cd CardDeck that is to be shuffled
         */
        public void shuffleDeck(CardDeck cd)
        {
          if(cd.deck.length < 1)
          {
            Logger.info("EMPTY DECK was shuffled.");
            return;
          }
        
          //use a random generator
          Random rdm = new Random();
          
          int nextCard = 0;
          
          //Shuffled deck
          String[] newCards = new String[cd.deck.length];
          
          String[] temp;
          
          int deckLength = cd.deck.length;
          
          //For every card in the deck select a random card and place 
          //it in the new deck.
          for(int i=0; i < deckLength - 1; i++)
          {
            nextCard = rdm.nextInt(cd.deck.length);
            newCards[i] = cd.deck[nextCard];
            
            temp = new String[cd.deck.length - 1];
            
            //Reassemble deck without the random card
            for(int j=0; j < nextCard; j++)
            {
              temp[j] = cd.deck[j];
            }
            for(int k=nextCard; k < cd.deck.length - 1; k++)
            {
              temp[k] = cd.deck[k+1];
            }
            cd.deck = temp;
            
          }
          
          //Last card from deck
          newCards[deckLength - 1] = cd.deck[0];
          
          //deck is now a shuffled deck
          cd.deck = newCards;
          return;
        }
       
        /**
         * This class returns the first card in the given deck, removes it from the deck.
         * @param cd CardDeck to draw a card from
         * @return The card drawn from the CardDeck
         */
        public String drawCard(CardDeck cd)
        {
        	String[] newDeck;
        	String drawedCard;
        	
        	try
        	{
        		drawedCard = cd.deck[0];
        		newDeck = new String[cd.deck.length - 1];
        	}
        	catch(ArrayIndexOutOfBoundsException e)
        	{
        		Logger.error("Cannot draw card. CardDeck is null");
        		return null;
        	}
        	//Reassemble deck without first card
        	for(int i=1; i < cd.deck.length; i++)
        	{
        		newDeck[i-1] = cd.deck[i];
        	}
          
        	cd.deck = newDeck;
          
        	Logger.info("Card has been drawn.");
        	return drawedCard;
        }
}
